package simulations;

import simulations.factory.EntityFactory;
import simulations.factory.EnvironmentFactory;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;


/**
 * Creates an component that is a viewer onto an animation.
 * 
 * @author Robert C. Duvall
 */
@SuppressWarnings("serial")
public class Canvas extends JComponent {
    // animate 25 times per second if possible (in milliseconds)
    public static final int ONE_SECOND = 1000;
    public static final int FRAMES_PER_SECOND = 25;
    // input state
    private static final JFileChooser ourChooser = new JFileChooser(System
            .getProperties().getProperty("user.dir"));
    private final static Logger LOGGER = Logger.getLogger(Canvas.class
            .getName());
    private Simulation mySimulation;

    /**
     * Initializes the canvas.
     * 
     * @param size
     * @param simulation
     */
    public Canvas (Dimension size, final Simulation simulation) {
        // request component size
        setPreferredSize(size);
        setFocusable(true);
        requestFocus();
        this.mySimulation = simulation;
        // make the bounding box's initial size the same as the canvas
        // initialize simulation
        loadModel();
    }

    public void setMySimulation (final Simulation mySimulation) {
        this.mySimulation = mySimulation;
    }

    /**
     * Paint the contents of the canvas.
     * <p/>
     * Never called by you directly, instead called by Java runtime when area of
     * screen covered by this container needs to be displayed (i.e., creation,
     * uncovering, change in status)
     * 
     * @param pen used to paint shape on the screen
     */
    @Override
    public void paintComponent (Graphics pen) {
        pen.setColor(Color.WHITE);
        pen.fillRect(0, 0, getSize().width, getSize().height);
        // paint the bounding box for debugging/ visualization purposes
        mySimulation.paint((Graphics2D) pen);
    }

    protected void loadModel () {
        int response = ourChooser.showOpenDialog(null);
        if (response == JFileChooser.APPROVE_OPTION) {
            mySimulation.add(EntityFactory.fromFile(ourChooser.getSelectedFile()));
        }
        int environment = ourChooser.showOpenDialog(null);
        if (environment == JFileChooser.APPROVE_OPTION) {
            EnvironmentFactory.fromFile(ourChooser.getSelectedFile(), mySimulation);
        }
    }

}
